<?php

namespace App\Http\Controllers\Ajax;

use App\Models\BalanceRecord;
use App\Models\GiftBuyUsed;
use App\Models\WxuserMcard;
use App\Repositories\OrderRepository;

use Illuminate\Http\Request;

class AboutPayController extends Controller
{
    /**
     * 购买礼品卡
     * @param Request $request
     * @param OrderRepository $repository
     */
    public function buyGiftCard(Request $request,OrderRepository $repository)
    {
        $case = $request->pay_type;
        $id = $request->id;
        $gift_card = $repository->getGiftCardById($id);
        if(empty($gift_card)) return $this->response->array(['code'=>403,'msg'=>'未找到礼品卡信息']);

        $gift_buy_model = new GiftBuyUsed();

        $wxuser_mcard = $this->getSeesionWxuseMcard();

        $data = [
            'buy_id_wxuser_mcard'=>$wxuser_mcard->id_wxuser_mcard,
            'gift_card_name'=>$gift_card->name,
            'buy_wxuser_mcard_name'=>$wxuser_mcard->member_optional_name,
            'buy_telephone'=>$wxuser_mcard->member_optional_telephone,
            'buy_date_time'=>now()->toDateTimeString(),
            'gift_no'=>$gift_buy_model->getGiftNo(),
            'pay_type'=>$case,
            'id_merchant_gift'=>$id,
            'id_merchant'=>session('web_merchant')->id_merchant,
            'order_no'=>$gift_buy_model->getOrderNo(),
            'pay_amount'=>(int) $gift_card->cash*100, //单位（分）
            //e181e3d1b8992a9472c34cd649fd0cb9
            'card_password'=>md5(md5('jiebaigiftcard'.str_random(16).$wxuser_mcard->id_wxuser_mcard))
        ];

        $insert_res = $gift_buy_model->create($data);

        if($insert_res){

//            if($request->pay_type)

            //调起支付
            switch ($case){
                case 'wxpay':

                    $res = $this->wxpay();

                    break;
                case 'alipay':

                    $res = $this->alipay();

                    break;
                case 'balancepay':
                    return ['code'=>404,'msg'=>'不支持的支付方式'];
//                    $res = $this->balancePay($insert_res,$gift_card->cash);

                    break;
                default:
                    return ['code'=>404,'msg'=>'不支持的支付方式'];
                    break;
            }
        }

        return $this->response->array($res);
    }

    protected function wxpay()
    {
        return ['code'=>303,'msg'=>'不好意思，支付方式暂未开通'];
    }

    protected function alipay()
    {
        return ['code'=>303,'msg'=>'不好意思，支付方式暂未开通'];
    }

    protected function balancePay($insert_res,$cash)
    {
        $wxuser_mcard = WxuserMcard::find($this->getSeesionWxuseMcard()->id_wxuser_mcard);

        if($cash*1 > $wxuser_mcard->remain_cash*1){
            return ['code'=>402,'msg'=>'账户余额不足'];
        }


        \DB::beginTransaction();
        try{
            $recode_data = [
                'id_wxuser_mcard'=>$wxuser_mcard->id_wxuser_mcard,
                'id_merchant'=>$wxuser_mcard->id_merchant,
                'value'=>-$cash,
                'title'=>'购买礼品卡',
                'desc'=>'礼品卡',
                'table_type'=>'gift_buy_used',
                'table_id'=>$insert_res->gift_buy_used_id,
                'created_at'=>now()->toDateTimeString(),
                'updated_at'=>now()->toDateTimeString(),
            ];
            \DB::table('balance_record')->insert($recode_data);

            \DB::table('wxuser_mcard')->where('id_wxuser_mcard',$wxuser_mcard->id_wxuser_mcard)->decrement('remain_cash',$cash);

            $insert_res->status = 'Y';

            $res = $insert_res->save();

            if($res) {
                \DB::commit();
                session(['web_wxuser_mcard'=>WxuserMcard::find($this->getSeesionWxuseMcard()->id_wxuser_mcard)]);
                return ['code'=>200,'msg'=>'购买成功'];
            }
            \DB::rollback();//事务回滚
            return ['code'=>500,'msg'=>'购买失败'];

        }catch(\Exception $e){
            \DB::rollback();//事务回滚
            return ['code'=>500,'msg'=>$e->getMessage()];
        }
        //创建余额记录
    }
}
